/**
 *
 * Author: zhuyehong
 * Date: 2013 8
 * web显示类型对应表(应当保证在子页面加载前初始化完毕)
 */
var WebTypeObj = ( function () {
  var enable = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 20], //
    disable = [10, 11, 12, 13, 14, 15, 16, 17, 8, 9, 20];

  function getEnable() {
    return enable;
  }

  function getDisable() {
    return disable;
  }

  function isEnable(val) {
    var i = 0;
    val = window.parseInt(val, 10);
    for (i = 0; i < enable.length; i += 1) {
      if (val === enable[i]) {
        return true;
      }
    }
    return false;
  }

  function isDisable(val) {
    var i = 0;
    val = window.parseInt(val, 10);
    for (i = 0; i < disable.length; i += 1) {
      if (val === disable[i]) {
        return true;
      }
    }
    return false;
  }

  function toDisable(val) {
    var i = 0;
    val = window.parseInt(val, 10);
    for (i = 0; i < enable.length; i += 1) {
      if (val === enable[i]) {
        return disable[i];
      }
    }
    return val;
  }

  function toEnable(val) {
    var i = 0;
    val = window.parseInt(val, 10);
    for (i = 0; i < disable.length; i += 1) {
      if (val === disable[i]) {
        return enable[i];
      }
    }
    return val;
  }

  return {
    isEnable: isEnable,
    isDisable: isDisable,
    toDisable: toDisable,
    toEnable: toEnable
  };
}());

/**
 * ModalControl Object
 *
 * Author: XYZ
 * Date: 2012 11 1
 */
( function () {
  //private variables
  var DIV, captureObj;

  /**private 辅助函数 begin*/
  function getMousePoint(event) {
    event = event || window.event;
    var m = (event.pageX || event.pageY) ? {
      x: event.pageX,
      y: event.pageY
    } : {
      x: event.clientX + top.document.body.scrollLeft - top.document.body.clientLeft,
      y: event.clientY + top.document.body.scrollTop - top.document.body.clientTop
    };
    return m;
  }

  function captureOn(mouseUpFn) {
    if (window.attachEvent) {
      captureObj.setCapture();
    } else if (window.addEventListener) {
      window.addEventListener("mouseup", up, true);
    }
  }

  function captureOff(mouseUpFn) {
    if (window.attachEvent) {
      captureObj.releaseCapture();
      captureObj.detachEvent("onlosecapture", onloseCapture);
    } else if (window.removeEventListener) {
      window.removeEventListener("mouseup", up, true);
    }
  }

  function up() {
    captureObj.onmousemove = null;
    captureOff(up);
  }

  function onloseCapture() {
    captureObj.onmousemove = null;
  }

  /**辅助函数  end*/

  /**class ModalControl*/
  ModalControl = function (div, dragIt) {
    DIV = div;
    captureObj = dragIt;
  };
  ModalControl.prototype = {
    dragStart: function (event) {
      var CXY = getMousePoint(event), BY = {
        x: CXY.x - (DIV.offsetLeft),
        y: CXY.y - (DIV.offsetTop)
      };

      DIV.onmousemove = function (event) {
        var CXY = getMousePoint(event);
        DIV.style.left = CXY.x - BY.x + "px";
        DIV.style.top = CXY.y - BY.y + "px";
      };

      DIV.onmouseup = up;
      captureOn(up);
    }
  }
}());

/**
 * 提示模态对话框
 * au  :zhuyehong
 */
var Modal = ( function () {
  var modalTips_callback = function () {
  }, popUpPageCloseCallback = function () {
  }, popUpPageBeforeCloseCallback = function () {
    return true;
  };

  function cover() {
    $("#coverPage").show();
  }

  function delCover() {
    //如果progress还要显示，不关闭 coverPage
    if ($("#progress").css("display") !== "block") {
      $("#coverPage").hide();
    }
  }

  /**
   * 显示进度条图片，msg可选，如果传入，显示相应文本信息
   * @param {String} msg, msg to show，optionally
   */
  function progress(msg) {
    cover();
    $("#progress").show();

    if (msg) {
      $("#progressTitle").text(msg);
    }
  }

  function delProgress() {
    $("#progress").hide();
    $("#loading").hide();
    $("#progressTitle").empty();
    delCover();
  }

  /**
   * 显示步骤集
   * @param {Array} steps, steps to show
   */
  function showSteps(arrSteps) {
    $("#events").empty();

    var i = 0, len = 0;
    for (i = 0, len = arrSteps.length; i < len; i += 1) {
      $("#events").append("<p style='margin-top:10px;'>" + arrSteps[i] + "</p>");
    }

    $("#events").show();
    $("#loading").show();
  }

  /**
   * @param {String} title,提示框标题
   * @param {String} inform,提示框信息
   * @param {String} msgType,提示框类型,'ok','error','cue','choice','reboot'
   * @param {Function} callback,提示框关闭是的回调，可选
   */
  function open(title, inform, msgType, callback) {
    cover();
    if (callback) {
      modalTips_callback = callback;
    } else {
      modalTips_callback = function () {
      };
    }

    $("#alert_title").empty();
    $("#alert_title").append(title);
    $("#alert_context").removeClass();
    $("#modalTips_btn_reboot").hide();
    $("#modalTips_btn_reactivate").hide();
    $("#modalTips_btn_submit").show();

    if (msgType === "choice") {
      $("#alert_context").addClass("question");
      $("#modalTips_btn_cancel").show();
    } else if (msgType === "error") {
      $("#alert_context").addClass("error");
      $("#modalTips_btn_cancel").hide();
    } else if (msgType === "reboot") {
      $("#alert_context").addClass('ok');
      $("#modalTips_btn_reboot").show();
      $("#modalTips_btn_submit").hide();
      $("#modalTips_btn_cancel").show();
    }
    else if (msgType === "reactivate") {
      $("#alert_context").addClass('ok');
      $("#modalTips_btn_reactivate").show();
      $("#modalTips_btn_submit").hide();
      $("#modalTips_btn_cancel").show();
    } else if (msgType === "DynamicEffect") {
      $("#alert_context").addClass('ok');
      $("#modalTips_btn_cancel").hide();
    }
    else {
      $("#alert_context").addClass(msgType);
      $("#modalTips_btn_cancel").hide();
    }

    $("#alert_inform").empty();
    $("#alert_inform").append(inform);
    $("#alert_window").show();

    setWidth();
  }

  function setWidth() {
    var width = $("#dialog_center").width();
    if (width < 350) {
      $("#dialog_center").css("width", "350px");
    } else {
      $("#dialog_center").css("width", "450px");
    }
  }

  /**
   * 提示框点击确定
   */
  function submit() {
    $("#alert_window").hide();
    delProgress();
    delCover();
    modalTips_callback(1);
  }

  /**
   * 提示框点击取消/关闭
   */
  function cancel() {
    $("#alert_window").hide();
    delCover();
    modalTips_callback(-1);
  }

  /**
   * @param {String} title, 弹出页面标题
   * @param {String} iframe_src, 弹出页面iframe 文件路径
   * @param {Function} closeCallback, 关闭弹出页面的回调
   * @param {Function} onBeforeClose, 关闭弹出页面前的回调
   * @param {String} IframeTDStyle, 弹出页面iframe的stype样式，用于设置高宽等
   */
  function openPopUpPage(title, iframe_src, closeCallback, onBeforeClose, IframeTDStyle) {
    cover();
    if (typeof (closeCallback) === "function") {
      popUpPageCloseCallback = closeCallback;
    } else {
      popUpPageCloseCallback = function () {
      };
    }
    if (typeof (onBeforeClose ) === "function") {
      popUpPageBeforeCloseCallback = onBeforeClose;
    } else {
      popUpPageBeforeCloseCallback = function () {
        return true;
      };
    }

    $("#wlan_guide_iframe").attr("style", IframeTDStyle);
    $("#dialog_tit_div").empty();
    $("#dialog_tit_div").append(title);
    iframe_src += ((iframe_src.indexOf("?") === -1) ? "?" : "&") + "r=" + top.VALIDATION_STRING;
    $("#wlan_guide_iframe").attr("src", iframe_src);
    $("#wlan_guide").show();
  }

  /**
   * @param {Boolean} exitManaul , 是否是手动退出
   */
  function closePopUpPage(exitManaul) {
    if (typeof (exitManaul) !== "undefined") {
      AutoParamConfig.var_guide_exit_manual(exitManaul);
    } else {
      AutoParamConfig.var_guide_exit_manual(false);
    }
    if (!popUpPageBeforeCloseCallback()) {
      //定义popUpPageBeforeCloseCallback()返回false，不关闭弹窗
      return;
    }

    $("#wlan_guide").hide();
    delCover();
    popUpPageCloseCallback();
  }

  /**
   * 访问不了服务网站，重定向到Error页面时，需要将popUpPageBeforeCloseCallback()去掉
   */
  function clearBeforeCloseFun() {
    popUpPageBeforeCloseCallback = function () {
      return true;
    };
  }

  return {
    progress: progress,
    delProgress: delProgress,
    showSteps: showSteps,
    open: open,
    setWidth: setWidth,
    submit: submit,
    cancel: cancel,
    openPopUpPage: openPopUpPage,
    closePopUpPage: closePopUpPage,
    clearBeforeCloseFun: clearBeforeCloseFun,
    delCover: delCover,
    cover: cover
  };
}());

/**
 * LMT 模块
 */
var LMT = ( function () {

  /**
   * 传入LMT结果，判断LMT命令成功与否
   * @param {String} data
   * @return {Boolean}
   */
  function isCmdSuccess(data) {
    if (typeof (data) === "undefined") {
      return false;
    }

    var resultIndex, resultEnd, result = "";
    if (typeof (data) === "object") {
      result = data.result || "";
    } else if (typeof (data) === "string") {
      resultIndex = data.indexOf("RESULT");
      resultEnd = data.indexOf("\n", resultIndex);
      result = data.substring(resultIndex, resultEnd);
    }

    if (result.indexOf("000") !== -1) {
      return true;
    } else {
      return false;
    }
  }

  /**
   * 异步LMT命令
   * @param {String} command
   * @param {Function} callback
   */
  function cmdSyn(command, callback) {
    /* command 命令中以符号 @ 开头表示抑制错误
     * errInhibit 为true 时，抑制错误
     */
    var errInhibit = command.indexOf('@') == 0 ? true : false;
    if (errInhibit) command = command.substring(1);

    command = command.replace(/[\r\n]+$/, '');
    command = encodeDATA(command);

    var url = "/telnetClient.asp" + "?r=" + VALIDATION_STRING, //
      tryCounts = 1, //
      doCmd = function () {
        $.ajax({
          url: url,
          async: true,
          type: "post",
          //contentType: "text/html",
          cache: false,
          timeout: 360010,
          data: {
            cmd: command
          },
          success: function (res) {
            if (-1 != command.indexOf("download complete")) {
              try {
                if (res.length < 1) {
                  callback("update_exception_sucess");
                } else {
                  callback(res);
                }
              } catch (e) {
                callback("update_exception_sucess");
              }
            } else {
              callback(res);
            }
          },
          error: function (XMLHttpRequest, textStatus, errorThrow) {
            tryCounts += 1;
            if (!errInhibit) Modal.progress(top.T.Main.PageWait);

            if (tryCounts > 3 && !errInhibit) {
              var errorStr = top.T.AlertInfo.LoadingCmdErrInfo + command;
              Modal.delProgress();
              Modal.open("Error", errorStr, "error");
            } else {
              doCmd();
            }
          }
        });
      };

    doCmd();
  }

  /**
   * 同步LMT命令
   * @param {String} command
   * @param {Number} time,  min seconds
   * @return {String}  lmt result
   */
  function cmdAsyn(command, time) {
    time = time || 30010;
    var url = "/telnetClient.asp" + "?r=" + VALIDATION_STRING, result = null;
    command = command.replace(/[\r\n]+$/, '');
    command = encodeDATA(command);

    $.ajax({
      url: url,
      type: "post",
      //contentType: "text/html",
      async: false,
      cache: false,
      timeout: time,
      data: {
        cmd: command
      },
      success: function (data) {
        result = data;
      },
      error: function (XMLHttpRequest, textStatus, errorThrow) {
        Modal.open("send fail", top.T.AlertInfo.ConnectFailInfo, "error");
        result = "send fail.";
      }
    });
    return result;
  }

  /**
   * 异步的WLAN LMT命令
   * @param {String} command
   * @param {Function} callback
   */
  function wlanCmdSyn(command, callback) {
    var url = "/C/wlanSession.asp" + "?r=" + VALIDATION_STRING;
    command = encodeDATA(command);

    $.ajax({
      url: url,
      async: true,
      type: "post",
      contentType: "text/html",
      cache: false,
      timeout: 360010,
      data: {
        cmd: command
      },
      success: function (data) {
        callback(data);
      },
      error: function (XMLHttpRequest, textStatus, errorThrow) {
        var result = "send fail.";
        callback(result);
      }
    });
  }

  /**
   * 同步的WLAN LMT 命名
   * @param {String} command
   * @param {Number} time ， min seconds
   * @return {String} LMT 命令结果
   */
  function wlanCmdAsyn(command, time) {
    time = time || 30010;
    var url = "/C/wlanSession.asp" + "?r=" + VALIDATION_STRING, result = null;
    command = encodeDATA(command);

    $.ajax({
      url: url,
      async: false,
      type: "post",
      contentType: "text/html",
      cache: false,
      timeout: time,
      data: {
        cmd: command
      },
      success: function (data) {
        result = data;
      },
      error: function (XMLHttpRequest, textStatus, errorThrow) {
        result = "send fail.";
      }
    });
    return result;
  }

  /**
   * 解析 LMT命令发挥字符串，返回对象
   * @param {String} ack , LMT命令返回字符串
   * @return Object
   */
  function parser(ack) {
    var header = getHeader(ack);
    header.name_val = [];
    // 不管正确与否，先添加name_val字段,保证name_val在出错返回时也是已定义的

    if (header.result === "000") {
      /* 为适应多实例格式进行的修改 begin
       CMD       :    get AuIpsecSta......[OK]
       RESULT    :    ACK 000
       HINT      :
       CONTENT   :   AuIpsecSta
       SecGwServer = "0"
       ConnState = "0"
       IPSecIP = "0"

       CONTENT   :   AuIpsecSta
       SecGwServer = "0"
       ConnState = "0"
       IPSecIP = "0"

       CONTENT   :   AuIpsecSta
       SecGwServer = "0"
       ConnState = "0"
       IPSecIP = "0"
       */
      var fstHeader = header.header, //
        b = fstHeader.indexOf(' '), //
        e = fstHeader.indexOf('.'), //
        structname = fstHeader.substring(b + 1, e), //
        reg = new RegExp("\r\nCONTENT +: +" + structname + "\r\n", "g");
      /* 为适应多实例格式进行的修改 end */

      var cmd = header.content.replace(reg, '');
      header.name_val = lmtContentParser(cmd);
    }
    return header;
  }

  /**
   * 从LMT命令返回字符串中提示返回头、返回体信息
   * @param {String} ack , LMT命令返回字符串
   * @return {Object}
   */
  function getHeader(ack) {
    /*result 错误代码说明:
     ACK 000  -> 命令执行成功
     ACK 001  -> 命令执行失败(有执行，执行失败)
     ACK 002  -> 命令格式不正确(没有执行,因为命令格式不正确)
     ACK 003  -> 命令不支持(格式正确，但不支持该命令)
     ACK ...
     .
     .
     .
     */
    var o = {
      text: ack,
      header: "",
      result: "",
      hint: "",
      content: ""
    }, emptyObj = {
      text: "",
      header: "",
      result: "005",
      hint: "",
      content: ""
    };

    if (ack.indexOf("\r\nCMD") !== 0) {
      return emptyObj;
    }

    var p_colon = ack.indexOf(":");
    if (p_colon === -1) {
      return emptyObj;
    }

    var p_enter = ack.indexOf("\n", 2);
    o.header = ack.substring(p_colon + 1, p_enter).replace(/\r/g, '').replace(/^ */, '');
    ack = ack.substring(p_enter + 1, ack.length);

    if (ack.indexOf("RESULT") !== 0) {
      return emptyObj;
    }

    p_colon = ack.indexOf(":");
    if (p_colon === -1) {
      return emptyObj;
    }
    p_enter = ack.indexOf("\n", 2);
    o.result = ack.substring(p_colon + 1, p_enter).replace(/\r/g, '');
    o.result = o.result.split("ACK")[1].replace(/ /g, '');
    ack = ack.substring(p_enter + 1, ack.length);

    if (ack.indexOf("HINT") !== 0) {
      return emptyObj;
    }

    p_colon = ack.indexOf(":");
    if (p_colon === -1) {
      return emptyObj;
    }
    p_enter = ack.indexOf("\n", 2);
    o.hint = ack.substring(p_colon + 1, p_enter).replace(/\r/g, '').replace(/^ */, '');
    ack = ack.substring(p_enter + 1, ack.length);

    if (ack.indexOf("CONTENT") !== 0) {
      return emptyObj;
    }

    p_colon = ack.indexOf(":");
    p_end = ack.lastIndexOf("->");
    if (p_colon === -1) {
      return emptyObj;
    }
    o.content = ack.substring(p_colon + 1, p_end);
    o.protoContent = $.trim(o.content);

    var fst_enter = o.content.indexOf("\r\n");
    var lst_enter = o.content.lastIndexOf("\r\n");
    o.content = o.content.substring(fst_enter + 2, lst_enter - 2);

    return o;
  }

  /**
   * 将LMT命令返回的参数值，格式化成数组对象返回
   * @param {String} content， LMT命令CONTENT的名值对部分
   * @return {Array} ,[Object]  ,Object={name,val,type}
   */
  function lmtContentParser(content) {
    /* 去掉可见的\"号字符 */
    var clone = content.replace(/\\\\/g, "**"), pArr;
    clone = clone.replace(/\\\"/g, "**");
//      clone = del_in_enter(clone);该函数没有用到，但是运行的过程中却占大量内存
    pArr = find_enter(clone);
    return make_name_val_pair(content, pArr);
  }

  function make_name_val_pair(content, pArr) {
    var name_val_str = [], name_val_pair = [], i = 0, len = 0, index = 0, o = {}, t_val = "", tmp = null, p = 0;

    for (i = 0, len = pArr.length; i < len; i += 1) {
      name_val_str.push(content.substring(index, pArr[i]));
      index = pArr[i] + 2;
    }

    for (i = 0, len = name_val_str.length; i < len; i += 1) {
      p = name_val_str[i].indexOf("=");
      o = {};
      o.name = $.trim(name_val_str[i].substring(0, p));
      o.val = $.trim(name_val_str[i].substring(p + 1, name_val_str[i].length));
      o.type = "integer";

      t_val = o.val.replace(/\n/g, "*");
      tmp = null;

      // 判断并解析Array、String类型
      if (t_val.charAt(0) === "[" && t_val.charAt(t_val.length - 1) === "]") {
        o.val = o.val.substring(1, o.val.length - 1);
        o.proto = o.val;
        o.type = "array";
      } else if (o.val.charAt(0) === "\"" && o.val.charAt(o.val.length - 1) === "\"") {
        o.val = o.val.substring(1, o.val.length - 1);
        o.type = "string";
      }
      name_val_pair.push(o);
    }
    return name_val_pair;
  }

  /**
   * 查找换行。
   * @param {String} cmd
   * @return {Array} \r\n所在的字符位置集合
   */
  function find_enter(conntent) {
    var fromindex = 0, pArr = [], i = 0;
    while (( i = conntent.indexOf("\r\n", fromindex)) !== -1) {
      pArr.push(i);
      fromindex = i + 2;
    }
    return pArr;
  }

  function del_in_enter(content) {
    var cArr = [], stack = false, cLength = content.length, i = 0, vCnt = 0, c = "";

    for (i = 0; i < cLength; i += 1) {
      c = content.charAt(i);
      if (c === "\"") {
        stack = !stack;
        cArr[vCnt] = c;
        vCnt += 1;
        continue;
      }

      if (stack && c === "\r" && content.charAt(i + 1) === "\n") {
        cArr[vCnt] = "**";
        vCnt += 1;
        i += 1;
        continue;
      }
      cArr[vCnt] = c;
      vCnt += 1;
    }
    return cArr.join("");
  }

  function wlanParser(data) {
    var o = {}, dataLineSet = data.split("\n");
    o.name_val = [];
    o.version = dataLineSet[0];
    o.result = dataLineSet[1];

    if (o.result === "OK") {
      o.content = dataLineSet[2];
      var ID_VALUE_STR_SET = dataLineSet.slice(3, dataLineSet.length), i = 0, name_val_obj = {
        name: "",
        val: ""
      }, v_name_val = [];

      for (i = 0; i < ID_VALUE_STR_SET.length; i += 1) {
        v_name_val = ID_VALUE_STR_SET[i].split("\t");
        name_val_obj.name = v_name_val[0];
        name_val_obj.val = v_name_val[1];

        if (name_val_obj.name.length > 0) {
          o.name_val.push(name_val_obj);
        }
      }
    }
    return o;
  }

  /**
   * 字符串转码
   * @param {Strng} str
   */
  function encodeDATA(str) {
    str = str.replace(/%/ig, '%25');
    str = str.replace(/#/ig, '%23');
    str = str.replace(/&/ig, '%D2');
    str = str.replace(/\+/ig, '%D3');
    return str;
  }

  /**
   * 字符串反转码
   * @param {String} str
   */
  function decodeDATA(str) {
    return str.replace(/%27/ig, "'");
  }

  return {
    isCmdSuccess: isCmdSuccess,
    cmdSyn: cmdSyn,
    cmdAsyn: cmdAsyn,
    wlanCmdSyn: wlanCmdSyn,
    wlanCmdAsyn: wlanCmdAsyn,
    parser: parser,
    wlanParser: wlanParser
  };
}());

/**
 * CMD command string builder.
 */
var CMDBuider = ( function () {
  /**
   * 构造LMT delete 命令
   * @param  {String} structName
   * @param  {Array} memberArr
   * @param  {Array} vArr
   * @return {String} cmd
   */
  function lmtCreateDelReq(structName, memberArr, vArr) {
    if (structName === null || structName === "" || memberArr.length <= 0 || memberArr.length !== vArr.length) {
      return "";
    }

    var cmdHeader = "delete " + structName + " : ", cmdContent = "", len = 0, maxID = 0, i = 0;
    for (i = 0, len = memberArr.length, maxID = len - 1; i < len; i += 1) {
      cmdContent += memberArr[i] + "= \"" + Transfer.symTransfer(vArr[i]) + "\"" + (i === maxID ? ";" : ", ");
    }

    return cmdHeader + cmdContent;
  }

  /**
   * 构造LMT add 命令
   * @param  {String} structName
   * @param  {Array} memberArr
   * @param  {Array} vArr
   */
  function lmtCreateAddReq(structName, memberArr, vArr) {
    if (structName === null || structName === "" || //
      memberArr.length <= 0 || memberArr.length !== vArr.length) {
      return "";
    }

    var structDesc = localDB.T_search("c_param", "StructName", structName), //
      WebTypeIndex = top.c_paramRowIndex.WebType, //
      MemberNameIndex = top.c_paramRowIndex.MemberName, //
      structDescInNeed = [], cnt = 0, len = 0, it = 0, //
      cmdHeader = "add " + structName + " : ", cmdContent = "", i = 0, maxID = 0, webType = 0;

    for (cnt = 0, len = structDesc.length; cnt < len; cnt += 1) {
      if (structDesc[cnt][MemberNameIndex] === memberArr[it]) {
        structDescInNeed.push(structDesc[cnt]);
        it += 1;
      }
    }

    for (i = 0, len = memberArr.length, maxID = len - 1; i < memberArr.length; i += 1) {
      webType = window.parseInt(structDescInNeed[i][WebTypeIndex], 10);
      if (webType === 12 || webType === 2 || webType === 20) {
        cmdContent += memberArr[i] + "=[" + Transfer.symTransfer(vArr[i]) + "]" + (i === maxID ? ";" : ", " );
      } else {
        cmdContent += memberArr[i] + "= \"" + Transfer.symTransfer(vArr[i]) + "\"" + (i === maxID ? ";" : ", ");
      }
    }

    return cmdHeader + cmdContent;
  }

  /**
   * 构造LMT get 命令,用于多实例
   * @param  {String} structName
   * @param  {Array} memberArr
   * @param  {Array} vArr
   */
  function lmtCreateGetMReq(structName, memberArr, vArr) {
    if (structName === null || structName === "" || memberArr.length <= 0 || memberArr.length !== vArr.length) {
      return "";
    }

    var cmdHeader = "get " + structName + " : ", cmdContent = "", i = 0, len = 0, maxID = 0;
    for (i = 0, len = memberArr.length, maxID = len - 1; i < len; i += 1) {
      cmdContent += memberArr[i] + "=\"" + Transfer.symTransfer(vArr[i]) + "\"" + (i === maxID ? ";" : ", " );
    }

    return cmdHeader + cmdContent;
  }

  /**
   * 构造LMT get 命令,用于单实例
   * @param  {String} structName
   * @return {String} get CMD
   */
  function lmtCreateGetReq(structName) {
    if (structName === null || structName === "") {
      return "";
    }

    return "get " + structName + ";";
  }

  /**
   * 构造LMT set 命令
   * @param  {String} structName
   * @param  {Array} memberArr
   * @param  {Array} vArr
   */
  function lmtCreateSetReq(structName, memberArr, vArr) {
    if (structName === null || structName === "" || memberArr.length <= 0 || memberArr.length !== vArr.length) {
      return "";
    }

    var structDesc = localDB.T_search("c_param", "StructName", structName), //
      WebTypeIndex = top.c_paramRowIndex.WebType, //
      MemberNameIndex = top.c_paramRowIndex.MemberName, //
      structDescInNeed = [], cnt = 0, it = 0, memLen = 0, structLen = 0;

    for (memLen = memberArr.length; it < memLen; it += 1) {
      cnt = 0;
      for (structLen = structDesc.length; cnt < structLen; cnt += 1) {
        if (structDesc[cnt][MemberNameIndex] === memberArr[it]) {
          structDescInNeed.push(structDesc[cnt]);
          break;
        }
      }
    }

    var cmdHeader = "set " + structName + " : ", cmdContent = "", i = 0, len = 0, maxID = 0, webType = 0;
    for (i = 0, len = memberArr.length, maxID = len - 1; i < len; i += 1) {
      webType = window.parseInt(structDescInNeed[i][WebTypeIndex], 10);
      if (webType === 12 || webType === 2 || webType === 20) {
        cmdContent += memberArr[i] + "=[" + Transfer.symTransfer(vArr[i]) + "]" + (i === maxID ? ";" : ", " );
      } else {
        cmdContent += memberArr[i] + "=\"" + Transfer.symTransfer(vArr[i]) + "\"" + (i === maxID ? ";" : ", " );
      }
    }

    return cmdHeader + cmdContent;
  }

  /**
   * 构造WLAN参数设置命令
   * @param {Array} vOid , OID数组
   * @param {Array} vArr , 对应的值数组
   */
  function wlanCreateSetReq(vOid, vArr) {
    if (vOid.length !== vArr.length) {
      return "";
    }

    var cmd = "lmt\017set\017", i = 0, len = 0;
    for (i = 0, len = vOid.length; i < len; i += 1) {
      if (vOid[i] === "" || vOid[i] === null) {
        continue;
      }
      cmd = cmd + vOid[i] + "=" + vArr[i] + "\017";
    }
    return cmd;
  }

  /**
   * 构造获取WLAN参数查询cmd命令
   * @param {Array} v_oid , OID数组
   */
  function wlanCreateGetReq(v_oid) {
    var cmd = "lmt\017get\017", i = 0, len = 0;

    for (i = 0, len = vOid.length; i < len; i += 1) {
      cmd = cmd + v_oid[i] + "\017";
    }
    return cmd;
  }

  return {
    lmtCreateDelReq: lmtCreateDelReq,
    lmtCreateAddReq: lmtCreateAddReq,
    lmtCreateGetMReq: lmtCreateGetMReq,
    lmtCreateGetReq: lmtCreateGetReq,
    lmtCreateSetReq: lmtCreateSetReq,
    wlanCreateSetReq: wlanCreateSetReq,
    wlanCreateGetReq: wlanCreateGetReq
  };
}());

var Struct = ( function () {
  /**
   * delete a struct
   * @param {String} structName,
   *  @param {Array} memberArr,
   * @param {Array} ValueArr,
   * @return {Object} returns a object which was parsed by LMT.parser()
   */
  function deleteStruct(structName, memberArr, vArr) {
    var cmd = CMDBuider.lmtCreateDelReq(structName, memberArr, vArr), //
      data = LMT.cmdAsyn(cmd);
    return LMT.parser(data);
  }

  /**
   * set 结构体
   *  @param {String} structName,
   *  @param {Array} memberArr,
   * @param {Array} ValueArr
   * @return {Object} returns a object which was parsed by LMT.parser()
   */
  function setStruct(structName, memberArr, vArr) {
    var cmd = CMDBuider.lmtCreateSetReq(structName, memberArr, vArr), //
      data = LMT.cmdAsyn(cmd);
    return LMT.parser(data);
  }

  /**
   * set WLAN 参数
   * @param {Array} oidArr
   * @param {Array} valueArr
   * @return {Object} returns a object wlanParse() parsed.
   */
  function setWlanParams(vOid, vArr) {
    var cmd = CMDBuider.wlanCreateSetReq(vOid, vArr), //
      data = LMT.wlanCmdAsyn(cmd);
    return LMT.wlanParser(data);
  }

  /**
   * 通过结构体名称，get一个结构体,同步方式
   * @param {String} structName
   * @return {Object} ack
   */
  function getStructByName(structName) {
    var ack = {}, WebTypeIndex = top.c_paramRowIndex.WebType, //
      MemberNameIndex = top.c_paramRowIndex.MemberName, //
      structDesc = localDB.T_search("c_param", "StructName", structName), //
      colsNames = localDB.T_getColNames("c_param"), //
      cmd = "", data = "", v_oid = [], j = 0, len = 0, desc = "";

    cmd = CMDBuider.lmtCreateGetReq(structName);
    data = LMT.cmdAsyn(cmd);
    ack = LMT.parser(data);
    ack.structType = "OAM";

    ack.structDesc = structDesc;
    ack.colsNames = colsNames;
    ack.sLength = structDesc.length;

    ack = resetChanged(ack);
    return ack;
  }

  /**
   *  异步get多个结构体，减少get多个结构体时间
   * @param{Array} structName Array
   * call callback with ack object array
   */
  function getStructsSyn(structNameArr, callback) {
    var cmd = "", i = 0, iLen = 0;

    for (iLen = structNameArr.length; i < iLen; i += 1) {
      cmd += CMDBuider.lmtCreateGetReq(structNameArr[i]);
      if (i !== iLen - 1) {
        cmd += "\017";
      }
    }

    LMT.cmdSyn(cmd, function (data) {
      var i = 0, iLen = 0, ack = {}, ackArr = [], data = data.split("\017"), //
        WebTypeIndex = top.c_paramRowIndex.WebType, //
        MemberNameIndex = top.c_paramRowIndex.MemberName, //
        colsNames = localDB.T_getColNames("c_param"), structDesc = null;

      if (data.length !== structNameArr.length) {
        //alert("Struct.getStructsSyn() error.");
        Modal.open(top.T.AlertInfo.OperationFail, "数据获取失败,请刷新", "error");
      }

      for (iLen = data.length; i < iLen; i += 1) {
        ack = {};
        ack = LMT.parser(data[i]);

        ack.structType = "OAM";
        structDesc = localDB.T_search("c_param", "StructName", structNameArr[i]);
        ack.structDesc = structDesc;
        ack.colsNames = colsNames;
        ack.sLength = structDesc.length;

        ack = resetChanged(ack);

        ackArr.push(top.objectClone(ack));
      }
      callback(ackArr);
    });
  }

  /**
   * 一次性保存多个结构体, 只返回一个命令的ack
   * @param{Array} cmd array, set命令数组
   * @return{Object} ack 有命令失败，返回第一个失败的ack；全部命令成功，返回最后一条命令的成功ack。
   */
  function setStructsByCmds(cmdArr) {
    var i = 0, iLen = 0, cmd = "", data = "", ack = {};
    for (iLen = cmdArr.length; i < iLen; i += 1) {
      cmd += cmdArr[i];
      if (i !== iLen - 1) {
        cmd += "\017";
      }
    }
    data = LMT.cmdAsyn(cmd);
    data = data.split("\017");
    for (i = 0, iLen = data.length; i < iLen; i += 1) {
      ack = LMT.parser(data[i]);
      if (ack.result !== "000") {
        // 出错时返回第一个出错的ack
        return ack;
      }
    }

    //执行到此，则所有ack都是成功的，返回最后一个成功的ack
    return LMT.parser(data[iLen - 1]);
  }

  /**
   * 异步方式 get 结构体
   * @param {String} StructName
   * @param {Function} callback
   */
  function getStructByNameSyn(structName, callback, errInhibit) {
    var structDesc = localDB.T_search("c_param", "StructName", structName), //
      colsNames = localDB.T_getColNames("c_param"), //
      cmd = CMDBuider.lmtCreateGetReq(structName);

    if (errInhibit) cmd = "@" + cmd;

    LMT.cmdSyn(cmd, function (data) {
      var ack = {};

      ack = LMT.parser(data);
      ack.structType = "OAM";
      ack.structDesc = structDesc;
      ack.colsNames = colsNames;
      ack.sLength = structDesc.length;

      ack = resetChanged(ack);
      callback(ack);
    });
  }

  /**
   * 获取多实例
   * @param {String} structName
   * @param {Array} memberNames
   * @param {Array} vArr
   * @return {Object} ack Object
   */
  function getMStructByName(structName, memberNames, vArr) {
    var cmd = CMDBuider.lmtCreateGetMReq(structName, memberNames, vArr), //
      data = LMT.cmdAsyn(cmd), ack = LMT.parser(data), //
      structDesc = localDB.T_search("c_param", "StructName", structName), //
      colsNames = localDB.T_getColNames("c_param"), i = 0, len = 0;

    ack.structDesc = structDesc;
    ack.colsNames = colsNames;
    ack.sLength = structDesc.length;

    ack = resetChanged(ack);

    return ack;
  }

  /**
   * 获取数组names对应的values数组
   * @return {Array} values array.
   */
  function getValuesByMemberName(structObj, names) {
    var ret = [], i = 0, len = names.length, j = 0, innerLen = structObj.name_val.length;
    for (i = 0; i < len; i += 1) {
      for (j = 0; j < innerLen; j += 1) {
        if (structObj.name_val[j].name === names[i]) {
          ret.push(structObj.name_val[j].val);
          break;
        }
      }
    }
    return ret;
  }

  /**
   * 获取数组IDs对应的values数组
   * @return {Array} values array.
   */
  function getValuesByMemberID(structObj, ids) {
    var ret = [], i = 0, j = 0, len = ids.length, innerLen = structObj.structDesc.length, MemberIDIndex = top.c_paramRowIndex.MemberID;
    for (i = 0; i < len; i += 1) {
      for (j = 0; j < innerLen; j += 1) {
        if (structObj.structDesc[j][MemberIDIndex] === ids[i]) {
          ret.push(structObj.name_val[j].val);
          break;
        }
      }
    }
    return ret;
  }

  /**
   * 重置超级用户的参数权限
   * @param {Object} ackObj
   * @return {Object} ackObj
   */
  function setSuperRole(ackObj) {
    if (top.role === top.Roles.Root) {
      var IsPrimaryKeyIndex = top.c_paramRowIndex.IsPrimaryKey, //
        WebTypeIndex = top.c_paramRowIndex.WebType, //
        i = 0, len = 0, t = "", t_len = 0, IsPrimary = 0;
      for (i = 0, len = ackObj.structDesc.length; i < len; i += 1) {
        t = ackObj.structDesc[i][WebTypeIndex];
        t_len = t.toString().length;

        if (t_len === 2 && window.parseInt(t, 10) < 0) {
          continue;
        }

        IsPrimary = window.parseInt(ackObj.structDesc[i][IsPrimaryKeyIndex], 10);
        if (IsPrimary !== 1) {
          ackObj.structDesc[i][WebTypeIndex] = WebTypeObj.toEnable(t);
        }
      }
    }

    return ackObj;
  }

  /**
   * 重置 参数的changed字段为false，表示用户未做修改
   * @param {Object} ackObj
   * @return {Object} ackObj
   */
  function resetChanged(ackObj) {
    if (ackObj.name_val) {
      var cnt = 0, len = 0;
      if ("OAM" === ackObj.structType) {
        for (cnt = 0, len = ackObj.name_val.length; cnt < len; cnt += 1) {
          ackObj.name_val[cnt].changed = false;
          ackObj.name_val[cnt].val = Transfer.deSymTransfer(ackObj.name_val[cnt].val);
        }
      } else {
        for (cnt = 0, len = ackObj.name_val.length; cnt < len; cnt += 1) {
          ackObj.name_val[cnt].changed = false;
        }
      }
    }

    return ackObj;
  }

  /**
   * 通过StructDesc判断此结构体是否为多实例
   * @param{Object} structDesc
   * @return {Boolean}
   */
  function isMulInstance(structDesc) {
    var i = 0, len = structDesc.length, IsPrimaryKeyIndex = top.c_paramRowIndex.IsPrimaryKey;
    for (i = 0; i < len; i += 1) {
      if (window.parseInt(structDesc[i][IsPrimaryKeyIndex], 10) === 1) {
        return true;
      }
    }
    return false;
  }

  /**
   *  通过StructDesc判断多实例结构体是否可添加
   * @param{Object} structDesc
   * @return {Boolean} 如果数据库不配置该值，默认为true.
   */
  function isMulInstanceAddable(structDesc) {
    var webTipsIndex = top.c_paramRowIndex.Level, websTips = "", canBeAdd = "";
    if (structDesc.length > 0) {
      websTips = Transfer.parseDbColumn(structDesc[0][webTipsIndex]);
      websTips = websTips.split("|");
      if (websTips.length >= 5) {
        canBeAdd = $.trim(websTips[4]);
        if (canBeAdd === "") {
          //default true
          return true;
        } else {
          return window.parseInt(canBeAdd, 10) === 1;
        }
      } else {
        return true;
      }
    }
    return false;
  }

  /**
   * 给StructDesc赋予新的StructID，构成一个新的结构体
   * @param{Object} structDesc,reference
   * @param{String} newStructID,
   */
  function setNewStructID(structDesc, newStructID) {
    var StructIDIndex = top.c_paramRowIndex.StructID, i = 0, len = 0;
    for (i = 0, len = structDesc.length; i < len; i += 1) {
      structDesc[i][StructIDIndex] = newStructID;
    }
  }

  /* web显示类型转换  */
  function toChangeable(structDesc) {
    var WebTypeIndex = top.c_paramRowIndex.WebType, oldType = -1, i = 0, len = 0, j = 0, jLen = 0;

    for (i = 0, len = structDesc.length; i < len; i += 1) {
      oldType = window.parseInt(structDesc[i][WebTypeIndex], 10);
      structDesc[i][WebTypeIndex] = WebTypeObj.toEnable(oldType);
    }
  }

  function toUnchangeable(structDesc) {
    var WebTypeIndex = top.c_paramRowIndex.WebType, oldType = -1, i = 0, len = 0, j = 0, jLen = 0;

    for (i = 0, len = structDesc.length; i < len; i += 1) {
      oldType = window.parseInt(structDesc[i][WebTypeIndex], 10);
      structDesc[i][WebTypeIndex] = WebTypeObj.toDisable(oldType);
    }
  }

  return {
    getStructByName: getStructByName,
    getStructByNameSyn: getStructByNameSyn,
    getStructsSyn: getStructsSyn,
    getMStructByName: getMStructByName,
    getValuesByMemberName: getValuesByMemberName,
    getValuesByMemberID: getValuesByMemberID,
    setStruct: setStruct,
    setStructsByCmds: setStructsByCmds,
    deleteStruct: deleteStruct,
    isMulInstance: isMulInstance,
    isMulInstanceAddable: isMulInstanceAddable,
    setNewStructID: setNewStructID,
    toChangeable: toChangeable,
    toUnchangeable: toUnchangeable,

    setWlanParams: setWlanParams
  };

}());

var MatrixStruct = ( function () {

  var MatrixStructObj = {}, StructObjs = [];

  /**
   * 解析结构如"StructID.MemberID"的数组
   * @param{Array} array of "StructID.MemberID"
   * @return{Array} [[structsIDs],[members]]
   */
  function matrixIdTransfer(matrix) {
    var structsIDs = [], memberIDs = [], i = 0, len = 0, s_m = [];

    for (i = 0, len = matrix.length; i < len; i += 1) {
      s_m = matrix[i].split('.');
      structsIDs.push(s_m[0]);
      memberIDs.push(s_m[1]);
    }
    return [structsIDs, memberIDs];
  }

  /**
   * @param{Array} [[structsIDs],[members]]
   * @return{Array} [[structsNames],[memberNames],[s_m]]
   */
  function matrixNameTransfer(sid_mem) {
    var s_m = [], structsNames = [], memberNames = [], //
      structNameIndex = top.c_paramRowIndex.StructName, //
      memberNameIndex = top.c_paramRowIndex.MemberName, //
      i = 0, len = 0, struct = "";

    for (i = 0, len = sid_mem[0].length; i < len; i += 1) {
      struct = localDB.T_search("c_param", "MemberID", sid_mem[1][i]);

      if (struct.length > 0) {
        structsNames.push(struct[0][structNameIndex]);
        memberNames.push(struct[0][memberNameIndex]);
        s_m.push(struct[0][structNameIndex] + '_' + struct[0][memberNameIndex]);
      } else {
        structsNames.push(sid_mem[0][i]);
        memberNames.push(sid_mem[1][i]);
        s_m.push(sid_mem[0][i] + '_' + sid_mem[1][i]);
      }
    }
    return [structsNames, memberNames, s_m];
  }

  /**
   *  判断x是否在set集合中
   * @param {String} x
   * @param {Array} String Array
   * @return{Boolean}
   */
  function isInSet(x, set) {
    var i = 0, len = 0;
    for (i = 0, len = set.length; i < len; i += 1) {
      if (x === set[i]) {
        return true;
      }
    }
    return false;
  }

  /**
   * 对传入的数组去冗余
   * @param{Array} arr
   * @return{Array} arr,去冗余后
   */
  function deleteRedundance(arr) {
    var retArr = [], cnt = 0, len = 0, si;
    for (cnt = 0, len = arr.length; cnt < len; cnt += 1) {
      si = arr[cnt];
      if (!isInSet(si, retArr)) {
        retArr.push(si);
      }
    }
    return retArr;
  }

  /**
   * 获取matrix struct的所有描述信息
   * @return{Array}
   */
  function matrixGetAllDesc(sid_mem) {
    var all_desc = [], members = sid_mem[1], i = 0, len = 0, mb = "";

    for (i = 0, len = members.length; i < len; i += 1) {
      mb = localDB.T_search("c_param", "MemberID", members[i]);
      if (mb.length > 0) {
        all_desc.push(mb[0]);
      }
    }
    return all_desc;
  }

  /**
   *  从数据库get所有用到的结构体值，然后以MatrixStructObj调用callback
   */
  function getValues(callback) {
    Struct.getStructsSyn(MatrixStructObj.structNameList, function (structObjs) {
      // 保存混合所涉及到的结构体
      StructObjs = structObjs;

      var i = 0, iLen = 0, structName = "", memberName = "", //
        j = 0, jLen = 0, k = 0, kLen, structNameIndex = top.c_paramRowIndex.StructName;

      //对name_val的每一个
      for (i = 0, iLen = MatrixStructObj.name_val.length; i < iLen; i += 1) {
        structName = MatrixStructObj.name_val[i].structName;
        memberName = MatrixStructObj.name_val[i].memberName;

        //从返回的结构体对象数组中找到所属结构体对象,找到就break
        for (j = 0, jLen = structObjs.length; j < jLen; j += 1) {
          if (structName === structObjs[j].structDesc[0][structNameIndex]) {
            //从找到的结构体对象中，找到对应的成员，找到就break
            for (k = 0, kLen = structObjs[j].name_val.length; k < kLen; k += 1) {
              if (memberName === structObjs[j].name_val[k].name) {
                MatrixStructObj.name_val[i].val = structObjs[j].name_val[k].val;
                MatrixStructObj.structDesc[i][top.c_paramRowIndex.WebType] = structObjs[j].structDesc[k][top.c_paramRowIndex.WebType];
                break;
              }
            }
            break;
          }
        }
      }

      //先push，因为callback里需要调用赋值
      CurrentStructs.push(MatrixStructObj);

      if (typeof (callback) === "function") {
        callback(MatrixStructObj);
      }
    });
  }

  /**
   * 将混合结构体的StructID替换为newStructID
   * @param{String} newStructID, new struct ID
   */
  function setNewStructID(newStructID) {
    var StructIDIndex = top.c_paramRowIndex.StructID, //
      MemberNameIndex = top.c_paramRowIndex.MemberName, i = 0, len = 0;
    for (i = 0, len = MatrixStructObj.structDesc.length; i < len; i += 1) {
      MatrixStructObj.structDesc[i][StructIDIndex] = newStructID;
      MatrixStructObj.structDesc[i][MemberNameIndex] = MatrixStructObj.sms[i];
    }
  }

  function process(matrixList) {
    var sids_memids = matrixIdTransfer(matrixList), //
      snames_mnames = matrixNameTransfer(sids_memids), n_v = {
        //保存structName，memberName，以便getValue函数赋值
        structName: '',
        memberName: '',

        name: '?',
        changed: false,
        type: 'string',
        val: '?'
      }, i = 0, len = 0;

    MatrixStructObj.structDesc = matrixGetAllDesc(sids_memids);
    MatrixStructObj.colsNames = localDB.T_getColNames("c_param");

    MatrixStructObj.structNames = snames_mnames[0];
    MatrixStructObj.memberNames = snames_mnames[1];
    MatrixStructObj.sms = snames_mnames[2];

    MatrixStructObj.memberIds = sids_memids[1];
    MatrixStructObj.structIds = sids_memids[0];
    MatrixStructObj.structNameList = deleteRedundance(snames_mnames[0]);
    MatrixStructObj.name_val = [];

    for (i = 0, len = MatrixStructObj.structDesc.length; i < len; i += 1) {
      // 需要克隆
      n_v.name = MatrixStructObj.sms[i];
      n_v.structName = MatrixStructObj.structNames[i];
      n_v.memberName = MatrixStructObj.memberNames[i];

      MatrixStructObj.name_val.push(objectClone(n_v));
    }
  }

  /**
   * 获取混合结构体
   * @param{Array} matrixList, Array of "StructID.MemberID"
   * @param{Function} callback , call this with the matrix Struct Object
   * @param{String} newStructID, new Struct ID for this matrix Struct.
   */
  function get(matrixList, Callback, newStructID) {
    MatrixStructObj = {};
    //标识是混合结构体，用于CurrentStructs保存是略过该结构体
    MatrixStructObj.matrix = true;
    StructObjs = [];
    process(matrixList);
    setNewStructID(newStructID);
    getValues(Callback);
  }

  /**
   * 保存Matrix struct
   */
  function set() {
    var i = 0, iLen = 0, sName = "", mName = "", j = 0, jLen = 0, k = 0, //
      StructNameIndex = top.c_paramRowIndex.StructName, //
      MemberNameIndex = top.c_paramRowIndex.MemberName, structObj = {}, cpStructObjs = top.objectClone(StructObjs);

    for (i = 0, iLen = MatrixStructObj.name_val.length; i < iLen; i += 1) {
      sName = MatrixStructObj.name_val[i].structName;
      mName = MatrixStructObj.name_val[i].memberName;

      // 对name_val的每一个参数，如果修改过，保存
      if (MatrixStructObj.name_val[i].changed) {

        //查找结构体
        for (j = 0, jLen = cpStructObjs.length; j < jLen; j += 1) {
          structObj = cpStructObjs[j];
          if (structObj.structDesc[0][StructNameIndex] === sName) {

            //查找member
            for (k = 0; k < structObj.name_val.length; k += 1) {
              if (structObj.name_val[k].name === mName) {
                structObj.name_val[k].val = MatrixStructObj.name_val[i].val;
                structObj.name_val[k].changed = true;
                break;
              }
            }
            break;
          }
        }
      }
    }

    return cpStructObjs;
  }

  return {
    get: get,
    set: set
  };
}());

/**
 * 生成数据库本地映像
 */
var DB = ( function () {
  function createDB() {
    var o = {};
    o.Tables = [];
    o.TableNames = [];

    o.CreateTable = function (name, cNames)/* (表名，表列名数组) */ {
      var t = new CreateTable(cNames.length);
      o.TableNames.push(name);
      t.T_setColName(cNames);
      o.Tables.push(t);
    };

    o.DeleteTable = function (name) {
      var index = -1, i = 0, len = 0;
      for (i = 0, len = o.TableNames.length; i < len; i += 1) {
        if (name === o.TableNames[i]) {
          index = i;
          break;
        }
      }

      if (index === -1 || index >= len) {
        return false;
      } else {
        o.TableNames.splice(index, 1);
        o.Tables.splice(index, 1);
        return true;
      }
    };

    o.T_getColNames = function (t_name) {
      var i = 0, len = 0;
      for (i = 0, len = o.TableNames.length; i < len; i += 1) {
        if (o.TableNames[i] === t_name) {
          break;
        }
      }

      if (i < len) {
        return o.Tables[i].T_getColNames();
      } else {
        throw "ERR: Not such table.";
      }
    };

    o.emptyCol = function (t_name, colName) {
      var i = 0, len = 0;
      for (i = 0, len = o.TableNames.length; i < len; i += 1) {
        if (o.TableNames[i] === t_name) {
          break;
        }
      }

      if (i < len) {
        return o.Tables[i].emptyCol(colName);
      } else {
        throw "ERR: Not such table.";
      }
    };

    o.T_getIndexByName = function (t_name, colName) {
      var i = 0, len = 0;
      for (i = 0, len = o.TableNames.length; i < len; i += 1) {
        if (o.TableNames[i] === t_name) {
          break;
        }
      }

      if (i < len) {
        return o.Tables[i].T_getColIndexByName(colName);
      } else {
        throw "ERR: Not such table.";
      }
    };

    o.T_import = function (t_name, arr) {
      var i = 0, len = 0;
      for (i = 0, len = o.TableNames.length; i < len; i += 1) {
        if (o.TableNames[i] === t_name) {
          break;
        }
      }

      if (i < len) {
        o.Tables[i].T_import(arr);
      } else {
        throw "ERR: No such table.";
      }
    };

    o.T_search = function (t_name, colName, val) {
      var i = 0, len = 0;
      for (i = 0, len = o.TableNames.length; i < len; i += 1) {
        if (o.TableNames[i] === t_name) {
          break;
        }
      }

      if (i < len) {
        return o.Tables[i].T_search(colName, val);
      } else {
        throw "ERR: Not such table.";
      }
    };

    o.T_getColumn = function (t_name, colName) {
      var i = 0, len = 0;
      for (i = 0, len = o.TableNames.length; i < len; i += 1) {
        if (o.TableNames[i] === t_name) {
          break;
        }
      }

      if (i < len) {
        return o.Tables[i].T_getColumn(colName);
      } else {
        throw "ERR: No such table.";
      }
    };

    o.T_reverse = function (t_name) {
      var i = 0, len = 0;
      for (i = 0, len = o.TableNames.length; i < len; i += 1) {
        if (o.TableNames[i] === t_name) {
          break;
        }
      }

      if (i < len) {
        return o.Tables[i].T_reverse();
      } else {
        throw "ERR: No such table.";
      }
    };

    return o;
  }

  function CreateTable(cCount) {
    var o = {};
    o.vector = [];
    o.totalCols = 0;
    o.colNames = [];

    o.T_setColName = function (nameArr) {
      if (nameArr.length === o.totalCols) {
        o.colNames = o.colNames.concat(o.colNames, nameArr);
      } else {
        throw "ERR: Table names length not equal table column length.";
      }
    };

    o.T_getColNames = function () {
      return o.colNames;
    };

    o.T_getColIndexByName = function (colName) {
      var index = -1, j = 0, len = 0;

      for (j = 0, len = o.colNames.length; j < len; j += 1) {
        if (colName === o.colNames[j]) {
          index = j;
          break;
        }
      }

      if (index >= len || index === -1) {
        return -1;
      } else {
        return index;
      }
    };

    o.T_import = function (arr) {
      if ((arr.length % o.totalCols) !== 0) {
        throw "ERR: Table total size not fit the cols.";
      }
      o.vector = o.vector.concat(o.vector, arr);
    };

    o.T_search = function (colName, val) {
      var index = -1, j = 0, len = 0;

      for (j = 0, len = o.colNames.length; j < len; j += 1) {
        if (colName === o.colNames[j]) {
          index = j;
          break;
        }
      }

      if (index >= len || index === -1) {
        throw "ERR: No such column.";
      }

      var matrix = [], inBlock = false;

      /* 用于处理特殊用户权限 , 处理超级用户权限  */
      //        var username = GetCookie('username');
      //        var WebTypeIndex =top.c_paramRowIndex.WebType;

      var i = index, v = "", b = 0, vector_block = [], exist;

      for (i = index, len = o.vector.length; i < len; i += o.totalCols) {
        v = o.vector[i];
        if (v == val) {
          b = i - index;
          vector_block = o.vector.slice(b, b + o.totalCols);
          matrix.push(vector_block);
        }
      }

      return matrix;
    };

    o.emptyCol = function (colName) {
      var index = -1, j = 0, len = 0;

      for (j = 0, len = o.colNames.length; j < len; j += 1) {
        if (colName === o.colNames[j]) {
          index = j;
          break;
        }
      }

      if (index >= len || index === -1) {
        throw "ERR:No such column.";
      }

      for (j = index, len = o.vector.length; j < len; j += o.totalCols) {
        o.vector[j] = "";
      }

      return true;
    };

    o.T_getColumn = function (colName) {
      var index = -1, j = 0, len = 0, cvArr = [];

      for (j = 0, len = o.colNames.length; j < len; j += 1) {
        if (colName === o.colNames[j]) {
          index = j;
          break;
        }
      }

      if (index >= len || index === -1) {
        throw "ERR:No such column.";
      }

      for (j = index, len = o.vector.length; j < len; j += o.totalCols) {
        cvArr.push(o.vector[j]);
      }

      return cvArr;
    };

    o.T_reverse = function () {
      var tempArr = [], begin = o.vector.length, colLen = o.colNames.length, i = 0;

      for (i = begin; i > -1; i -= colLen) {
        tempArr = tempArr.concat(o.vector.slice(i - colLen, i));
      }
      o.vector = tempArr;
      return true;
    };

    o.init = function (c) {
      o.totalCols = c;
    };

    o.init(cCount);
    return o;
  }

  return {
    createDB: createDB
  };
}());

/**
 * 转换
 */
var Transfer = ( function () {
  function symTransfer(value) {
    return value.toString().replace(/\\/g, "\\\\").replace(/\"/g, "\\\"");
  }

  function deSymTransfer(value) {
    return value.toString().replace(/\\\\/g, "\\").replace(/\\\"/g, "\"");
  }

  /**
   * 解析统一数据库的列参数信息配置，返回当前产品对应部分的信息
   * @param{String} str, 原始的信息
   */
  function parseDbColumn(str) {
    // 不再需要该处理
    return str;

  }

  /**
   * 创建标签
   * @param {String} typeDesc_in，类型描述
   * 目前只需支持 等号(=)与逗号(,)的转义
   */
  function wtListParser(typeDesc_in, memberID) {
    var i = 0, tmp = "", arr = [], selectNames = [], selectVals = [], //
      typeDesc = typeDesc_in.replace(/\\\\,/g, '\017'), j = 0, //
    //*实现下拉列表的中英文切换
      itemsArry = typeDesc.split("||");
    if (itemsArry.length === 2) {
      if (itemsArry[0] === "" || top.Language === "EN") {
        j = 1;
      }
      if (itemsArry[1] === "" && top.Language === "EN") {
        j = 0;
      }
    }

    items = itemsArry[j].split(",");

    //items = typeDesc.split(",");
    for (i = 0; i < items.length; i += 1) {
      items[i] = items[i].replace(/\017/g, ',');
      tmp = items[i].replace(/\\\\=/g, "\017");
      arr = tmp.split('=');
      if (arr.length === 2) {
        arr[0] = arr[0].replace(/\017/g, "=");
        arr[0] = $.trim(arr[0]);
        arr[1] = arr[1].replace(/\017/g, "=");
        arr[1] = $.trim(arr[1]);
        if (arr[0] == "" || arr[1] == "") {
          alert("成员" + memberID + "的TypeDesc字段,错误配成x=''或''=y的形式了,应配成X=Y形式!");
          break;
        } else {
          selectNames.push(arr[0]);
          selectVals.push(arr[1]);
        }
      } else {
        alert("成员" + memberID + "的TypeDesc字段" + typeDesc_in + "应配成X=Y形式!");
        break;
      }
    }

    return {
      selectNames: selectNames,
      selectVals: selectVals
    };
  }

  return {
    symTransfer: symTransfer,
    deSymTransfer: deSymTransfer,
    parseDbColumn: parseDbColumn,
    wtListParser: wtListParser
  };
}());

var DeviceInfo = ( function () {
  var version, productClass;

  /**
   * 返回版本号的第一个.后面的部分，用于加在所有URL的后面，实现每个版本不同
   * 不使用Math.random() 因为这样相同版本的每个链接都是不同的文件，不利于调测
   * 用这个部分版本号，即实现了每个版本的更新，又避免了调测时的问题
   */
  function getPartialVersion() {
    if (!version) {
      getByLMT();
    }
    return version;
  }

  function getProductClass() {
    if (!productClass) {
      getByLMT();
    }
    return productClass;
  }

  function getByLMT() {
    var data = LMT.cmdAsyn("get DeviceInfo;"), ack = null, model = "ModelName";
    if (USER.hasModule(Branch.Modules.LTE_EN)) {
      model = "ProductClass";
    }

    if (LMT.isCmdSuccess(data)) {
      ack = LMT.parser(data);

      $(ack.name_val).each(function (i) {
        if (this.name === model) {
          productClass = this.val;
        }
      });
      $(ack.name_val).each(function (i) {
        if (this.name === "SoftwareVersion") {
          version = this.val.substring(this.val.indexOf(".") + 1);
        }
      });
    }
  }

  return {
    getPartialVersion: getPartialVersion,
    getProductClass: getProductClass
  };
}());
